package com.icaptcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.Console;
import com.icaptcha.model.CaptchaProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class captcha {
    private static final long VALUE_TIME=2*60*1000L;
@Autowired
private CaptchaProperties captchaProperties;
    @RequestMapping("/getCaptcha")
public void getCaptcha(HttpServletResponse response, HttpSession session){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("image/jpeg");
        try {
            //定义图形验证码的长和宽
            LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
            String code=lineCaptcha.getCode();
            System.out.println(code);
            session.setAttribute(captchaProperties.getSession().getKey(),code);
            session.setAttribute(captchaProperties.getSession().getDate(),new Date());
            lineCaptcha.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/check")
public Boolean check(HttpSession session,String captcha){
        if(!StringUtils.hasLength(captcha)){
            return false;
        }
        String code=(String) session.getAttribute(captchaProperties.getSession().getKey());
        Date date=(Date) session.getAttribute(captchaProperties.getSession().getDate());

        if(captcha.equals(code)&&date!=null&&(System.currentTimeMillis()-date.getTime()<VALUE_TIME)){
return true;
        }
return false;
    }



}
